from api.stockcollect_api import *
from flask import Blueprint,request,jsonify
import pandas as pd
# import akshare as ak
from flask import jsonify
import datetime
import json
from utils.stockTocode import * 
import tushare as ts
import akshare as ak



stockInfo = Blueprint('stockInfo',__name__)
@stockInfo.route('/longhu',methods=['GET'])
def get_longhu():
    # 序号 股票代码 股票名称 收盘价 对应值 成交量 成交额
    titlename=["序号","股票代码","股票名称","收盘价","对应值","成交量","成交额"]
    longhu_data = ak.stock_sina_lhb_detail_daily()
    # print(longhu_data)
    xuhao_list = list(longhu_data["序号"])
    code_list = list(longhu_data["股票代码"])
    name_list = list(longhu_data["股票名称"])
    close_list = list(longhu_data["收盘价"])
    duiyingzhi_list = list(longhu_data["对应值"])
    deal_list = list(longhu_data["成交量"])
    dealmone_list = list(longhu_data["成交额"])

    longhu_result = []
    data_length = len(xuhao_list)

    for index in range(data_length):
        line_dic = {}
        line_dic["serial"]=str(xuhao_list[index])
        line_dic["stockNumber"] = str(code_list[index])
        line_dic["stockName"] = str(name_list[index])
        line_dic["closingPrice"] = str(close_list[index])
        line_dic["correspondingValue"] = str(duiyingzhi_list[index])
        line_dic["tradeVolume"] = str(deal_list[index])
        line_dic["tradeAmount"] = str(dealmone_list[index])

        longhu_result.append(line_dic)

    longhu_result = json.dumps(longhu_result, ensure_ascii=False)
    return longhu_result
    # res1=json.dumps(res,ensure_ascii=False)
    # print(res1/)

    # filename="F:\\shixunWorkSpace\\baFeiTeWorkspace\\Quantitative_server\\Quantity_Flask\\handler\\longhu.json"
    # with open('a.json','w') as file_obj:
    #     file_obj.write(res1)
    # print(res)
    return res

#今开，股票名，最低，最高，昨收，成交量，总市值
#数据处理，将tushare获取的数据传到这里进行json封装
@stockInfo.route('/mystockInfo',methods=['GET','POST'])
def collect_Info():
    userId = request.args.get("userId")
    result = get_mycollect_stock(userId)
    #print(result)
    #解析json数据获得股票名result
    res_list = []
    for stock in result:
        stockName = stock['stockName']
        code = name_to_code(stockName)
        res_list.append(get_myinfo_by_code(code))
    return jsonify(res_list)
    #return "success"


#股票查询界面
#股票查询页面查股东比列value/name
@stockInfo.route('/searchInfo',methods=['GET','POST'])
def search_stock():
    stock = request.args.get("stock")
    userid = request.args.get("userId")
    #print(stock)
    if stock.isdigit():
        stockinfo = get_info_by_code(stock,userid)
    else:
        stockcode = name_to_code(stock)
        if stockcode == 'not exist':
            return "name not found"
        stockinfo = get_info_by_code(stockcode,userid)

    
    id = stock
    print("----------")
    print(id)
    day_result,week_result,month_result = get_collect_stock(id)
    
    res = {}
    res["stockinfo"] = stockinfo
    res["dayline"]=day_result
    res["weekline"]=week_result
    res["monthline"] = month_result
    res = json.dumps(res, ensure_ascii=False)
    return res


#========================================获取单只股票日，周，月，===============================================
#  日期 开盘(open)，收盘(close)，最低(lowest)，最高(highest),起始时间"2018-09-19"

def get_collect_stock(id):
    today = datetime.date.today()
    data_index = pd.date_range("2018-09-19", today)  # DataFrame 第一列时间获取不到
    data_list = [pd.Timestamp(x).strftime("%Y-%m-%d") for x in data_index.values][-210:]
    AStock_data = ts.get_hist_data(id)
    open_list = list(AStock_data["open"])[-210:]
    close_list = list(AStock_data["close"])[-210:]
    low_list = list(AStock_data["low"])[-210:]
    high_list = list(AStock_data["high"])[-210:]

    # 日线获取
    day_line = []
    for i in range(210):
        line_list = []
        line_list.append(data_list[i])
        line_list.append(open_list[i])
        line_list.append(close_list[i])
        line_list.append(low_list[i])
        line_list.append(high_list[i])
        day_line.append(line_list)

    # 周线获取
    week_line = []
    i = 0
    start = 0
    end = 7
    for i in range(30):
        line_list = []
        line_list.append(data_list[start + 4])
        line_list.append(sum(open_list[start:end]) / 7)
        line_list.append(sum(close_list[start:end]) / 7)
        line_list.append(sum(low_list[start:end]) / 7)
        line_list.append(sum(high_list[start:end]) / 7)
        week_line.append(line_list)
        start = end
        end += 7

    # 月线获取
    month_line = []
    i = 0
    start = 0
    end = 30
    for i in range(7):
        line_list = []
        line_list.append(data_list[start + 15])
        line_list.append(sum(open_list[start:end]) / 30)
        line_list.append(sum(close_list[start:end]) / 30)
        line_list.append(sum(low_list[start:end]) / 30)
        line_list.append(sum(high_list[start:end]) / 30)
        month_line.append(line_list)
        start = end
        end += 30
    return day_line, week_line, month_line
    

#增加股票界面
@stockInfo.route('/addStock',methods=['GET','POST'])
def add_stock():
    stockName = request.args.get("stockName")
    userId = request.args.get("userId")
    #stockName = "宁德时代"
    #userId = 1
    print(userId)
    print(stockName)
    result = add_collect_stock({
        "stockName" : stockName,
        "userID" : userId
    })
    return jsonify(result)

#删除股票界面
@stockInfo.route('/delStock',methods=['GET','POST'])
def del_stock():
    stockName = request.args.get("stockName")
    userId = request.args.get("userId")
    result = del_collect_stock({
        "stockName" : stockName,
        "userID" : userId
    })
    return jsonify(result)

    